package com.sprucetec.live.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sprucetec.live.base.entity.User;
import com.sprucetec.live.common.util.OssUtil;
import com.sprucetec.live.common.webcontext.LoginUserContext;
import com.sprucetec.live.constants.SprucetecConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName RestInterceptor
 * @Description:
 * @Author Kenny
 * @Date 2020/5/25
 **/
@Slf4j
public class RestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        try {
            String realIp = OssUtil.getRealIp(request);
            request.getSession().invalidate();
            User user = new User();
            user.setIp(realIp);
            LoginUserContext.setUser(user);
            return true;
        } catch (Exception e) {
            log.error("LoginInterceptor catch到异常", e);
            //发生异常,返回异常信息
            request.getSession().invalidate();
            this.returnJson(response, SprucetecConstant.OpCode.SSO_NOT_LOGIN, "rest接口请求失败！", false);
            return false;
        }
    }


    private void returnJson(HttpServletResponse response, int rspCode, String rspMsg, boolean success) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            JSONObject resultJson = new JSONObject();
            resultJson.put("rspCode", rspCode);
            resultJson.put("rspMsg", rspMsg);
            resultJson.put("success", success);

            writer = response.getWriter();
            writer.print(resultJson.toJSONString());

        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }
}
